package smallfrench.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;

import javax.swing.JPanel;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;

/**
 * Pour afficher les noméros de ligne
 *
 */
@SuppressWarnings("serial")
public class NumeroteurLignes extends JPanel {

	private final static int LARGEUR = 40;

	MTextPane pane;

	public NumeroteurLignes(Editeur editeur) {
		super();
		setOpaque(true);
		pane = editeur.getTextPane();

		pane.addCaretListener(new CaretListener() {
			@Override
			public void caretUpdate(CaretEvent arg0) {
				rafraichir();
			}
		});
	}

	public void rafraichir() {
		setPreferredSize(new Dimension(LARGEUR, pane.getHeight()));
		repaint();
	}

	@Override
	public void paint(Graphics graphics) {
		Graphics2D g = (Graphics2D)graphics;
		g.setRenderingHint(
				RenderingHints.KEY_TEXT_ANTIALIASING,
				RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);

		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(), getHeight());

		// On trace une ligne grise à droite
		g.setColor(new Color(200, 200, 200));
		g.drawLine(getWidth() - 1, 0,
				getWidth() - 1, getHeight());

		g.setColor(Color.GRAY);

		FontMetrics fm = g.getFontMetrics(pane.getFont());
		int fontHeight = fm.getHeight();

		int nombreLignes = pane.getDocument().
				getDefaultRootElement().getElementCount();

		double fFontHeight;
		try {
			Rectangle r = pane.modelToView(pane.getText().length());
			fFontHeight = (r.getY() - fm.getDescent()) / (nombreLignes - 1);
		} catch (BadLocationException e) {
			fFontHeight = fontHeight;
		}

		for (int ligne = 0 ; ligne <= nombreLignes ; ligne++) {
			g.drawString(Integer.toString(ligne),
					0,
					(int) (ligne * fFontHeight));
		}

	}
}
